﻿using System;
using System.Xml;

namespace NJabber.Stream.Elements
{
    public class PresenceStanza : Stanza
    {
        public static readonly int MinPriorityValue = -127;
        public static readonly int MaxPriorityValue = 128;

        private int? priority;

        public PresenceStanza() : base("presence")
        {}

        public PresenceStanza(string type) : base("presence")
        {
            Type = type;
        }

        public string Availability { get; set; }

        public int? Priority
        {
            get { return priority; }
            set
            {
                if(value != null && (value.Value > MaxPriorityValue || value.Value < MinPriorityValue))
                {
                    throw new ArgumentException();
                }
                priority = value;
            }
        }

        public string StatusText { get; set; }

        protected override void WritePayload(XmlWriter writer)
        {
            base.WritePayload(writer);
            WriteAvailabilityStatus(writer);
            WriteStatusText(writer);
            WritePriority(writer);
        }

        private void WriteAvailabilityStatus(XmlWriter writer)
        {
            if (!string.IsNullOrEmpty(Availability)) writer.WriteElementString("show", Availability);
        }

        private void WriteStatusText(XmlWriter writer)
        {
            if (string.IsNullOrEmpty(StatusText)) return;
            writer.WriteElementString("status", StatusText);
        }

        private void WritePriority(XmlWriter writer)
        {
            if (Priority == null) return;
            writer.WriteElementString("priority", Priority.Value.ToString());
        }

        public override bool Equals(object obj)
        {
            PresenceStanza presence = obj as PresenceStanza;
            if (presence == null) return false;
            return Equals(presence);
        }

        public bool Equals(PresenceStanza presence)
        {
            return base.Equals(presence) 
                && AreValuesEquals(Availability, presence.Availability)
                && AreValuesEquals(Priority, presence.Priority)
                && AreValuesEquals(StatusText, presence.StatusText);
        }
    }
}
